//
//  MahjongWaitingVC.m
//  Mahjong
//
//  Created by 饶首建 on 17/6/29.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "MahjongWaitingVC.h"
#import "MahjongLoginVC.h"
#import "MahjongMainVC.h"
#import "MahjongMainGameVC.h"

#import "PlayerHeadAndNameView.h"

#import <SDWebImage/UIImageView+WebCache.h>


@interface MahjongWaitingVC ()
@property (weak, nonatomic) IBOutlet UIView *userContainerView;
@property (weak, nonatomic) IBOutlet UILabel *playerTipLabel;
@property (weak, nonatomic) IBOutlet UILabel *ruleTipLabel;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;

@end

@implementation MahjongWaitingVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchCallBack:) name:NOTIFICATION_MATCH_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchBackCallBack:) name:NOTIFICATION_MATCH_BACK_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchChangeSeatCallBack:) name:NOTIFICATION_MATCH_CHANGE_SEAT_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchReconnectCallBack:) name:NOTIFICATION_MATCH_RECONNECT_CALLBACK object:nil];

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - Notification
- (void)matchReconnectCallBack:(NSNotification*)notification{
    [self goPage:notification.object type:YES];
}
- (void)goPage:(NSDictionary *)dic type:(BOOL)isReconnect{
    dic = [NSDictionary recursionResultJson4NullclassToNullstring:dic];
    MatchModel *mm = [MatchModel parseDic:dic];
    
    if (isReconnect) {
        [PlayerModel ownerInstance].playerId = mm.me.playerId;
        [PlayerModel ownerInstance].playerName = mm.me.playerName;
    }

    if (mm.players.count >= 4 && mm.isSeted) {
        MahjongMainVC *vc = [[MahjongMainVC alloc]init];
        vc.matchModel = mm;
        [self presentViewController:vc animated:YES completion:^{}];
    }
}

- (void)matchChangeSeatCallBack:(NSNotification *)notification{
    UIViewController *vc =self.presentingViewController;
    while (![vc isKindOfClass:[MahjongLoginVC class]]) {
        vc = vc.presentingViewController;
    }
    [vc dismissViewControllerAnimated:YES completion:^{}];
}

- (void)matchCallBack:(NSNotification *)notification{
    NSDictionary *dic = notification.object;
    dic = [NSDictionary recursionResultJson4NullclassToNullstring:dic];

    NSDictionary *pmDic = dic[@"newPlayer"];
    if (pmDic) {
        _playerTipLabel.text = NSStringFormat(@"%@进入牌局",pmDic[@"name"]);
        [UIView animateWithDuration:0.3 animations:^{
            _playerTipLabel.alpha = 1;
        } completion:^(BOOL finished) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:0.3 animations:^{
                    _playerTipLabel.alpha = 0;
                }];
            });
        }];
    }
    
    MatchModel *mm = [MatchModel parseDic:dic];
    _matchModel = mm;
    [self updatePlayers];
    
    if (mm.players.count >= 4 && mm.isSeted) {
        MahjongMainGameVC *vc = [[MahjongMainGameVC alloc]init];
//        MahjongMainVC *vc = [[MahjongMainVC alloc]init];
        vc.matchModel = mm;
        [self presentViewController:vc animated:YES completion:^{}];
    }
}

- (void)matchBackCallBack:(NSNotification *)notification{
    NSDictionary *dic = notification.object;
    dic = [NSDictionary recursionResultJson4NullclassToNullstring:dic];
    NSDictionary *pmDic = dic[@"player"];
    _playerTipLabel.text = NSStringFormat(@"%@离开牌局",pmDic[@"name"]);
    [UIView animateWithDuration:0.3 animations:^{
        _playerTipLabel.alpha = 1;
    } completion:^(BOOL finished) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.3 animations:^{
                _playerTipLabel.alpha = 0;
            }];
        });
    }];
    
    MatchModel *mm = [MatchModel parseDic:dic[@"match"]];
    _matchModel = mm;
    [self updatePlayers];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _ruleTipLabel.hidden = _matchModel.isSeted;
    
    _playerTipLabel.alpha = 0;
    
    [self updatePlayers];
}

- (void)updatePlayers{
    for (UIView *v in _userContainerView.subviews) {
        [v removeFromSuperview];
    }
    
    float containerW = _userContainerView.frame.size.width;
    float margin = (containerW - (_matchModel.players.count * 120))/(_matchModel.players.count+1);
    float w = 120;
    float h = 190;
    for (int i=0; i< _matchModel.players.count; i++) {
        PlayerModel *pm = _matchModel.players[i];
        PlayerHeadAndNameView *view = [PlayerHeadAndNameView playerHeadAndNameView];
        
        view.headImageView.layer.cornerRadius = view.headImageView.frame.size.width/2;
        view.headImageView.layer.masksToBounds = YES;
        
        view.frame = CGRectMake(margin*(i+1)+i*w, 0, w, h);
        
        view.nameLabel.text = pm.playerName;
        if ([pm.playerId isEqualToString:[PlayerModel ownerInstance].playerId]) {
            view.nameLabel.textColor = UIColorHex(66B5F0);
        }
        NSString *avatar = pm.avatar;
        [view.headImageView sd_setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:UIImageWithName(@"default_head")];
        if (avatar.length == 0) {
            view.firstLabel.text = [pm.playerName substringToIndex:1];
        }else{
            view.firstLabel.text = @"";
        }
        
        [_userContainerView addSubview:view];
    }
}

- (IBAction)backAction:(id)sender {
    NSString *url = NSStringFormat(@"%@/Matches/%@/users/%@/leave",BASE_URL,_matchModel.matchId,[PlayerModel ownerInstance].playerId);
    [HttpUtil sendRequestURL:url method:POST param:@{} success:^(id response) {
        UIViewController *vc =self.presentingViewController;
        while (![vc isKindOfClass:[MahjongLoginVC class]]) {
            vc = vc.presentingViewController;
        }
        [vc dismissViewControllerAnimated:YES completion:^{}];
    } fail:^(NSString *errorStr) {
        [Hud hudText:errorStr inView:self.view];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            UIViewController *vc =self.presentingViewController;
            while (![vc isKindOfClass:[MahjongLoginVC class]]) {
                vc = vc.presentingViewController;
            }
            [vc dismissViewControllerAnimated:YES completion:^{}];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
